/**
 * 缓存 存储localStorage
 */

import {encrypt,crypto} from '@/libs/utils.js'
import router from '../router/index'
import { Message  } from 'element-ui'

// 加密
export const setStore = (name, content) => {
  if (!name) return
  if (typeof content !== 'string') {
    content = JSON.stringify(content)
  }
  // window.localStorage.setItem(name, encrypt(content)) 
  // window.localStorage.setItem(name, content) 
  const now = Date.now();
  /*1 分钟计算 (1000*60)  计算出总失效时间 (1000 * 60 * expired) now + 失效总分钟 算出最大存储时间*/
  let expired = 24
  let source = { value: "" };
  if (expired) {
      source.value = JSON.stringify({ expired: now + (1000 * 60 * expired) });
  } 
  window.localStorage.setItem(name, content,source.value) 
}

/**
 * 不加密
 * @param {*} name 
 * @param {*} content 
 * @returns 
 */
export const NsetStore = (name, content) => {
  if (!name) return
  if (typeof content !== 'string') {
    content = JSON.stringify(content)
  }
  window.localStorage.setItem(name, content)
}

/**
 * 获取localStorage
 */
// 获取并且解密
export const getStore = name => {
  if (!name) return
  var v = window.localStorage.getItem(name)
  
  const now = Date.now(); 
  let source = {  value: null }; 
  /* 获取 localStorage 存储信息 赋值给 source 对象 */
  source.value = JSON.parse(localStorage.getItem(name));

  /* 如果key 有效  判断当前时间 是否超过 失效时间 */
  if (source.value) { 
      if (now >= source.value.expired) {
          /* 超过失效时间 删除 储存内容  */ 
          localStorage.removeItem(name);
          Message.error("Token已过期")
          router.push('/login')
          return;
      } 
  } 
 
  if (v == null) {
    return ''
  }
  if(v != ""){  
    // console.log(v)
    // JSON.parse(decrypt(v))
    // console.log(JSON.parse(decrypt(window.localStorage.getItem(name))))
    return v
  } 
  return v
}
// 获取
export const NgetStore = name => {
  if (!name) return
  let v = window.localStorage.getItem(name)
  if (v == null) {
    return ''
  }
  return v
} 

/**
 * 删除localStorage
 */
export const removeStore = name => {
  if (!name) return
  window.localStorage.removeItem(name)
}
